package com.android.nextBus.JSON;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

/**
 * This class is responsible for doing a get request on a specific URL 
 * The Url does not have to return a JSON object, but does so in this case
 *
 */
public class JSONBusStopHTTPGet {

	
	/**
	 * @param u_r_l the url for our get request
	 * @return a string representation of the JSON object
	 */
	public static String readBusStopJSONFeed(String u_r_l,Intent intent) {

		
		StringBuilder builder = new StringBuilder();
		//Client for our Get request
		HttpClient client = new DefaultHttpClient();
		//get request object that takes our Url as a parameter
		HttpGet httpGet = new HttpGet(u_r_l);
		try {
			//Execute the get request
			HttpResponse response = client.execute(httpGet);
			//get status of the the response
			StatusLine statusLine = response.getStatusLine();
			//and get status code to check for errors
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(content));
				
				String line;
				while ((line = reader.readLine()) != null) {
					//Build a string consisting of our JSON object returned fronm 
					//the Http get request
					builder.append(line);
				}
				intent.putExtra("failedGetRequest", false);
			} else {
				Log.e("!!!!!!!!!!", "Failed to download file");
				intent.putExtra("failedGetRequest", true);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			intent.putExtra("failedGetRequest", true);
		} catch (IOException e) {
			e.printStackTrace();
			intent.putExtra("failedGetRequest", true);
		}
		//return the JSON Representation of the String
		return builder.toString();
	}
}


